import axios, { AxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

import store from '@/store'
import router from '@/router/'

const request = axios.create({
  baseURL: import.meta.env.VITE_BASE_API_URL as string,
  withCredentials: true,
})

request.interceptors.request.use(config => {
  // config.headers['Content-Type'] = 'application/json'

  const token = localStorage.getItem('token')
  token && (config.headers['Authorization'] = `Bearer ${token}`)

  return config
})

const successStatus = [200, 201, 202, 203, 204, 205, 206, 207, 208, 226]

const noAuthStatus = [401, 403, 410000]

const errorStatus = [
  ...noAuthStatus,
  400,
  404,
  405,
  406,
  408,
  409,
  410,
  411,
  412,
  413,
  414,
  415,
  416,
  417,
  418,
  421,
  422,
  423,
  424,
  426,
  428,
  429,
  431,
  451,
  500,
  501,
  502,
  503,
  504,
  505,
  506,
  507,
  508,
  510,
  511,
]


function errorHandler(msg: string, status: number) {
  if (noAuthStatus.includes(status)) {
    store.commit('setToken', '')
    store.commit('setUserInfo', {})

    router.push({
      path: '/signin',
      query: { redirect: router.currentRoute.value.path },
    })
  }

  ElMessage.error({
    message: msg || status + '',
    showClose: true,
  })

  return Promise.reject(msg)
}

request.interceptors.response.use(
  response => {
    const { data } = response
    const { status, msg } = data

    if (errorStatus.includes(status)) {
      errorHandler(msg, status)
    } else {
      return data
    }
  },
  error => {
    const { status, msg } = error
    errorHandler(msg, status)
  }
)

export default async <T = any>(config: AxiosRequestConfig) => {
  const res = await request(config)
  return (res.data || res) as T
}

// export default request
